package com.forestar.xzk.threadFor;

import com.forestar.xzk.appcommon.CpuUtils;
import com.forestar.xzk.logs.LogTag;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * 线程基本操作，包括子线程操作，主线程操作，互相结合切换，线程池操作等
 *
 * 使用rxJava实现，
 */
public class ThreadUtils {

    private static ExecutorService service = new ThreadPoolExecutor(0, getCpuNUmber() * 4,
            60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());

    public static void execute(Runnable runnable){
        service.execute(runnable);
        int threadCount = ((ThreadPoolExecutor)service).getActiveCount();
        LogTag.e("===threadCount===", threadCount+"");
    }

    private static int getCpuNUmber() {
        int value = CpuUtils.getCoreNumber();
        if (value < 2) value = 2;
        return value;
    }

    public interface ICallBack{
        <T> void onResult(T t);
    }

    //主线程做操作
    public static void doOnUIThread(UITask uiTask){
        Consumer<UITask> consumer = new Consumer<UITask>() {
            @Override
            public void accept(UITask uiTask) throws Exception {
                uiTask.doOnUI();
            }
        };
        Observable.just(uiTask)
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(consumer);
    }

    //io线程做操作
    public static void doOnThread(ThreadTask threadTask){
        Consumer<ThreadTask> consumer = new Consumer<ThreadTask>() {
            @Override
            public void accept(ThreadTask uiTask) throws Exception {
                uiTask.doOnThread();
            }
        };
        Observable.just(threadTask)
                  .observeOn(Schedulers.io())
                  .subscribe(consumer);
    }

    public interface ThreadTask{
        void doOnThread();
    }

    public interface UITask{
        void doOnUI();
    }
}